package edu.neu.cs6515.xml;

import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

/**
 * Returns XML String representation of a {@link XMLResultMarshaller} object.
 */
public final class XMLResultMarshaller {

    private final JAXBContext context;
    private final Marshaller marshaller;

    /**
     * Initalizes marshaller
     * 
     * @throws JAXBException
     *             if there's a problem initializing a JAXBContext
     */
    public XMLResultMarshaller() throws JAXBException {
        context = JAXBContext.newInstance(Results.class);
        marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
    }

    /**
     * Turns given Seq object into a XML string representation
     * 
     * @param results
     *            Sequence Object to be transformed
     * @return XML String
     */
    public String marshall(final Results results) {
        final StringWriter stringWriter = new StringWriter();
        try {
            marshaller.marshal(results, stringWriter);
        } catch (final JAXBException e) {
            e.printStackTrace();
        }
        return stringWriter.toString();
    }
}
